<?php

namespace Largezhou\Admin\Components;

use Largezhou\Admin\ContentBuilder;

class Component extends ContentBuilder
{
    /**
     * @var string 前端组件名,默认为 'admin-'.kebab_case(类名)
     */
    protected $component;
    protected $props = [];

    public function __call($name, $arguments)
    {
        // 快捷设置props中的某个值
        if (array_key_exists($name, $this->props)) {
            return $this->props($name, ...$arguments);
        }

        throw new \ErrorException('Call to undefined method '.__CLASS__.'::'.$name.'()');
    }

    /**
     * 获取或者设置前端组件类型.
     *
     * @param string $name
     *
     * @return $this|string
     */
    public function component($name = null)
    {
        if (is_null($name)) {
            if (empty($this->component)) {
                $this->component($this->makeComponent());
            }

            return $this->component;
        }

        $this->component = $name;

        return $this;
    }

    /**
     * 生成默认的组件名
     *
     * @return string
     */
    protected function makeComponent()
    {
        return 'admin-'.kebab_case(class_basename(static::class));
    }

    /**
     * 获取或者设置前端组件的props.
     *
     * @param      $props
     * @param null $value
     *
     * @return array|mixed|$this
     */
    public function props($props = null, $value = null)
    {
        $argNum = func_num_args();
        // 如果没有传参,则直接返回所有值不为null的props
        if ($argNum === 0) {
            return array_filter($this->props, function ($prop) {
                return !is_null($prop);
            });
        }

        // 如果只传了第一个参数,且为字符串,则取出该prop的值
        if ($argNum === 1 && is_string($props)) {
            return $this->props[$props] ?? null;
        }

        // 如果第一个参数为数组,则批量修改props;否则单个修改
        if (is_array($props)) {
            $this->props = array_merge($this->props, array_intersect_key($props, $this->props));
        } elseif (array_key_exists($props, $this->props)) {
            $this->props[$props] = $value;
        }

        return $this;
    }

    protected function variables()
    {
        return [
            'component' => $this->component(),
            'props'     => $this->props(),
        ];
    }
}
